//
//  NewsViewController.m
//  NEWS
//
//  Created by lanou on 16/4/6.
//  Copyright © 2016年 孙金龙. All rights reserved.
//

#import "NewsViewController.h"
#import "CollectionViewCell.h"
#import "TableViewCell.h"
#import "UIImageView+WebCache.h"
#import "CollectionModel.h"
#import "RequestManager.h"
#import "TableViewModel.h"
#import "TableViewCell2.h"
#import "DetailController.h"
#import "MJRefresh.h"
#define KWidth [UIScreen mainScreen].bounds.size.width
#define KHeight  [UIScreen mainScreen].bounds.size.height
@interface NewsViewController ()<UICollectionViewDelegateFlowLayout,UICollectionViewDataSource,UICollectionViewDelegate,UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate,UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UICollectionView *Collection;
@property (weak, nonatomic) IBOutlet UIScrollView *ScrollView;
@property (nonatomic,strong) NSArray *titleArray;// 头条等标题数组


@property (nonatomic,strong) NSMutableArray *bigArray;// 装在小数组的大数组


@property (nonatomic,strong)NSMutableArray *scrollImageArray;// 转载上面轮播图的图片的url数组
@property (nonatomic,assign)NSInteger index;// 寻找对应的indexpatch
@property (nonatomic,strong)NSMutableArray *collectModelArray;
@property (nonatomic,strong)NSMutableArray *modelArray;// tableView对应的model
@property (nonatomic,strong)UIImageView *image;
@property (nonatomic,strong)TableViewModel *model;// 轮播图的数据
@property (nonatomic,strong)UILabel *countLabel;// 轮播图上变化的数字的label
@end

@implementation NewsViewController

// 网络请求
- (void)requestWithCount:(NSInteger)count tableView:(UITableView *)tableView
{
    NSArray *kurl = @[Headlines,Recreation,Military,Economic,History,Technology,Sports];
    [RequestManager requestWithUrl:kurl[count] requestType:RequestTypePost parDic:nil finish:^(NSData *data) {
        NSArray *bigArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSDictionary *bigDic = bigArray[0];
        NSDictionary *bigDic2 = bigArray[1];
        NSArray *itemArray = bigDic[@"item"];
        NSArray *itemArray2 = bigDic2[@"item"];
        // 解析tableView的数据
        NSMutableArray *array  = [NSMutableArray array];
        
        for (NSDictionary *modelDic in itemArray)
        {
            TableViewModel *model = [[TableViewModel alloc] init];
            [model setValuesForKeysWithDictionary:modelDic];
            NSDictionary *style = modelDic[@"style"];
            model.images = style[@"images"];
            [array addObject:model];
        }
        // 将小数组装到大数组中;
        [_bigArray replaceObjectAtIndex:count withObject:array];
        // 解析轮播图的数据
        _scrollImageArray = [NSMutableArray array];
        for (NSDictionary *modelDic in itemArray2) {
            TableViewModel *model = [[TableViewModel alloc] init];
            _model = model;
            [model setValuesForKeysWithDictionary:modelDic];
            [_scrollImageArray addObject:model];
        }
        // 轮播图
        UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, KWidth, KHeight/4)];
        scroll.contentSize = CGSizeMake(KWidth*_scrollImageArray.count, KHeight/4);
        scroll.backgroundColor = [UIColor purpleColor];
        scroll.pagingEnabled = YES;
        scroll.showsHorizontalScrollIndicator = NO;
        scroll.showsVerticalScrollIndicator = NO;
        scroll.bounces = YES;
        scroll.delegate = self;
        scroll.contentOffset = CGPointMake(0, 0);
        for (int i = 0; i < _scrollImageArray.count; i++)
        {
            TableViewModel *model = _scrollImageArray[i];
            UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(i*KWidth, 0, KWidth, KHeight/4)];
            [image sd_setImageWithURL:[NSURL URLWithString:model.thumbnail]];
            image.backgroundColor = [UIColor lightGrayColor];
            
            UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, KHeight/4-30, KWidth, 20)];
            titleLabel.textColor = [UIColor whiteColor];
            titleLabel.font = [UIFont systemFontOfSize:13];
            titleLabel.text = model.title;
            [image addSubview:titleLabel];
            // 变化的数字的label
            _countLabel = [[UILabel alloc] initWithFrame:CGRectMake(KWidth-50, KHeight/4-30, 40, 35)];
            _countLabel.textColor = [UIColor whiteColor];
            _countLabel.text = [NSString stringWithFormat:@"%d/%ld",i+1,_scrollImageArray.count];
            [scroll addSubview:image];
            [image addSubview:_countLabel];
        }
        tableView.tableHeaderView = scroll;
        // 添加手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapCountAction:)];
        [scroll addGestureRecognizer:tap];
        // 申请完数据结束刷新
        [tableView.header endRefreshing];
        dispatch_async(dispatch_get_main_queue(), ^{
            [tableView reloadData];
        });
    } error:^(NSError *error) {
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor blackColor];
    self.navigationController.navigationBarHidden = YES;
    // 系统会自动改frame让他不要改
    self.automaticallyAdjustsScrollViewInsets = NO;
    _bigArray = [@[@"1",@"2",@"3",@"4",@"5",@"6",@"7"] mutableCopy];
    for (int i = 0; i <7;i++)
    {
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(i*KWidth, 0, KWidth, KHeight-70) style:UITableViewStylePlain];
        tableView.tag = 1000+i;
        tableView.dataSource = self;
        tableView.delegate = self;
        [tableView registerClass:[TableViewCell class] forCellReuseIdentifier:@"Tcell"];
        [tableView registerClass:[TableViewCell2 class] forCellReuseIdentifier:@"Tcell2"];
        tableView.frame = CGRectMake(i*KWidth, 0, KWidth, KHeight-70);
        _ScrollView.scrollsToTop = YES;
        _ScrollView.bounces = NO;
        // tableView.bounces =NO;
        [_ScrollView addSubview:tableView];
        // 请求数据
        [self requestWithCount:i tableView:tableView];
    }
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.Collection registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"Ccell"];
    _Collection.frame = CGRectMake(50, 20, KWidth-100, 50);
    _titleArray = @[@"头条",@"娱乐",@"军事",@"经济",@"历史",@"科技",@"体育" ];
    _collectModelArray = [NSMutableArray array];
    // 创建model用来解决collectionView cell的复用问题 顺带加载数据
    for (int i = 0; i < _titleArray.count; i++)
    {
        
        CollectionModel *model = [[CollectionModel alloc] init];
        [_collectModelArray addObject:model];
        if (i == 0)
        {
            model.isSelect = YES;
        }
    }
    self.ScrollView.contentSize = CGSizeMake(KWidth*_titleArray.count, KHeight-70);
    self.ScrollView.contentOffset = CGPointMake(0, 0);
    self.ScrollView.pagingEnabled = YES;
    self.ScrollView.bounces = NO;
    self.ScrollView.delegate = self;
    
    // 上拉刷新
    int count = 0;
    for (UITableView *tableView in _ScrollView.subviews)
    {
        if ([tableView isKindOfClass:[UITableView class]])
        {
//            tableView.header = [MJRefreshHeader headerWithRefreshingBlock:^{
//                [self requestWithCount:count tableView:tableView];
//            }];
            [tableView addLegendHeaderWithRefreshingBlock:^{
                [self requestWithCount:count tableView:tableView];

            }];
            count ++;
        }
    }
}

// 给顶上的scrollview添加手势
- (void)tapCountAction:(UITapGestureRecognizer *)tap
{
    DetailController *detail = [[DetailController alloc] init];
    detail.model = _model;
    [self.newsNav pushViewController:detail animated:YES];
    detail.nav = self.newsNav;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
     NSArray *array = _bigArray[tableView.tag-1000];
    if ([array isKindOfClass:[NSString class]]) {
        return 0;
    }
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 根据不同的tableView返回不同的cell
        NSArray *array = _bigArray[tableView.tag-1000];
        TableViewModel *model = array[indexPath.row];
        if (model.images == nil)
        {
            TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Tcell" forIndexPath:indexPath];
            cell.model = model;
            return cell;
        }
        else
        {
            TableViewCell2 *cell = [tableView dequeueReusableCellWithIdentifier:@"Tcell2" forIndexPath:indexPath];
            cell.model = model;
            return cell;
        }
}

// 返回cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *array = _bigArray[tableView.tag -1000];
        TableViewModel *model = array[indexPath.row];
        if (model.images != nil)
        {
            return 140;
        }
        else
        {
            return 100;
        }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *array = _bigArray[tableView.tag-1000];
    TableViewModel*model = array[indexPath.row];
    DetailController *detail = [[DetailController alloc] init];
    detail.model = model;
    [self.navigationController pushViewController:detail animated:YES];
    detail.nav = self.navigationController;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _titleArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Ccell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.title.text = _titleArray[indexPath.row];
    CollectionModel *model = _collectModelArray[indexPath.row];
    if (model.isSelect)
    {
        cell.title.textColor = [UIColor orangeColor];
    }
    else
    {
        cell.title.textColor = [UIColor blackColor];
    }
        return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(55, 40);
}

// 点击collection的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.ScrollView.contentOffset = CGPointMake(indexPath.row*KWidth, 0);
    
    for (CollectionModel *model in _collectModelArray)
    {
        model.isSelect = NO;
    }
    CollectionModel *model = _collectModelArray[indexPath.row];
    model.isSelect = !model.isSelect;
     _Collection.contentOffset = CGPointMake(45*indexPath.row, 0);
    [self.Collection reloadData];
}

// scrollView结束减速的方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 只有当大的scrollview滚动的时候才刷新界面
    if ([_ScrollView isEqual:scrollView])
    {
        [_Collection reloadData];
         int a = (int)_ScrollView.contentOffset.x/KWidth;
        // _ScrollView.contentOffset = CGPointMake(KWidth*a, 0);
        CollectionModel *model = _collectModelArray[a];
        for (CollectionModel *model in _collectModelArray)
        {
            model.isSelect = NO;
        }
        model.isSelect = !model.isSelect;
        // 用来显示cell的位置
        _Collection.contentOffset = CGPointMake(45*a, 0);
    }
    else if ([_Collection isEqual:scrollView])
    {
        
    }
    else
    {
        
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
